import random

from django.http import HttpRequest
from django.http import HttpResponse
from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.request import Request
from rest_framework.response import Response

from rest_framework.views import APIView
from meiduo_mall.libs.captcha.captcha import captcha
# Create your views here.
# GET：^image_code/(?P<img_id>[\w-]+/$
# 生成图片验证码
from meiduo_mall.utils.exceptions import logger
from meiduo_mall.utils.yuntongxun.sms import CCP
from users.models import User
from verifications import constants
from verifications import serializers
from celery_tasks.sms.task import send_sms_code


class ImageCodeView(APIView):
    def get(self,request,img_id):
    # 1,接受参数uuid
    # 2校验参数
    # 3生成图片验证码
        text, image = captcha.generate_captcha()
    # 4将图片的uuid及text保存到redis中
        print(text)
        redis_conn=get_redis_connection('verify_codes')
        redis_conn.setex("img_%s"%img_id,constants.IMAGE_CODE_REDIS_EXPIRES,text)
    # 5把数据返回给前端
        return HttpResponse(image,content_type='image/jpg')


#   url(r'^image_checked/?text=xxx&fmobile=xxx')
class SMSCodeView(GenericAPIView):
    # 接受数据
    serializer_class = serializers.ImageCodeCheckSerializer

    def get(self,request:Request,mobile):
    # 校验参数
        params=request.query_params
        # print(params)
        serializers=self.get_serializer(data=params)
        serializers.is_valid(raise_exception=True)
    # 发送短信
        sms_code="%06d"%random.randint(0,999999)
        print(sms_code)
        redis_conn=get_redis_connection('verify_codes')
        pl=redis_conn.pipeline()
        pl.setex("sms_%s"%mobile,constants.SMS_CODE_REDIS_EXPIRES,sms_code)
        pl.setex("send_flag_%s"%mobile,constants.SEND_SMS_CODE_INTERVAL,1)
        pl.execute()
    #     try:
    #         ccp=CCP()
        expires=constants.SMS_CODE_REDIS_EXPIRES//60
    #         result=ccp.send_template_sms(mobile,[sms_code,expires],constants.SMS_CODE_TEMP_ID)
    #     except Exception as e:
    #         logger.error("发送验证码短信[异常][ mobile: %s, message: %s ]" % (mobile, e))
    #         return Response({"message","failed"},status=status.HTTP_503_SERVICE_UNAVAILABLE)
    #     else:
    #         if result==0:
    #             logger.info("发送验证码短信[成功][ mobile: %s]" % mobile)
    #             return Response({"message":"ok"})
    #         else:
    #             logger.jwarning("发送验证码短信[异常][ mobile: %s]" % mobile)
    #             return Response({"message": "failed"},status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    # # 返回处理结果
    # 使用celery发送短信验证码
        print("执行了")
        # send_sms_code.delay(mobile,sms_code,expires,constants.SMS_CODE_TEMP_ID)

        return Response({"message": "OK"})


class UsernameView(APIView):
    def get(self,request,username):
        count=User.objects.filter(username=username).count()
        data={
            "username":username,
            "count":count
        }
        return Response(data)

# GET r'^mobile/(?P<mobile>1[34578]\d{9})/&',views.MobileView.as_view()
class MobileView(APIView):
    def get(self,request,mobile):
        count = User.objects.filter(mobile=mobile).count()
        data = {
            "mobile": mobile,
            "count": count
        }
        return Response(data)